const express = require('express');
const SerialPort = require('serialport');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json()); // 用于解析JSON格式的请求体
app.use(bodyParser.urlencoded({ extended: true })); // 用于解析URL编码的请求体

// 路由处理函数，返回所有串口信息
app.get('/serial-ports', async (req, res) => {
    try {
        const ports = await SerialPort.list();
        res.json(ports); // 将串口信息作为JSON响应返回
    } catch (err) {
        console.error('Error occurred:', err);
        res.status(500).send('Internal Server Error');
    }
});

// 启动HTTP服务器
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});